<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <div :class="isMobile ? 'mobile-button-group horizontal' : ''">
        <BaseButton @click="go(-1)">
          {{ t('common.back') }}
        </BaseButton>
        <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
          {{ t('action.save') }}
        </BaseButton>
      </div>
    </template>
    <!--    表单-->
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules as FormRules"
      label-width="200px"
      :class="isMobile ? 'mobile-form' : ''"
    >
      <!-- 基本信息区块 -->
      <div :class="isMobile ? 'form-section' : ''">
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('order.contract_type')"
          required
        >
          <el-select
            v-model="form.contract_type"
            :placeholder="t('order.contract_type')"
            @change="handleChangeContractType"
          >
            <el-option
              v-for="item in contractTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('dealerAssetManagement.customerName')"
          required
        >
          <el-input v-model="form.customer.username" clearable disabled placeholder="">
            <!-- <template #append>
              <el-button size="small" text type="success" @click="handleOpenCustomer">{{
                t('dealerAssetManagement.select')
              }}</el-button>
            </template> -->
          </el-input>
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('dealerAssetManagement.customerEmailAddress')"
        >
          <el-input v-model="form.customer.email" clearable disabled placeholder="" />
        </el-form-item>
        <el-form-item :class="isMobile ? 'mobile-item' : 'w-60%'" :label="t('order.orderCode')">
          <el-input v-model="form.order_no" clearable :disabled="!isOrderNoEditable">
            <template #append>
              <el-button
                size="small"
                :type="isOrderNoEditable ? 'success' : 'primary'"
                @click="toggleOrderNoEdit"
              >
                {{ isOrderNoEditable ? t('common.done') : t('common.edit') }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('order.signatory')"
          required
        >
          <el-input v-model="state.inputDisplayText.signatory" clearable disabled placeholder="">
            <template #append>
              <el-button size="small" text type="success" @click="handleOpenSignatory">{{
                t('dealerAssetManagement.select')
              }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="t('order.signing_date')"
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          prop="signing_date"
          required
        >
          <el-date-picker
            v-model="form.signing_date"
            type="date"
            :placeholder="t('common.pleaseSelect') + t('order.signing_date')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('order.transfer_payment_info')"
          v-if="form.contract_type == 2"
          :required="form.contract_type == 2"
        >
          <el-select
            v-model="form.transfer_payment_info"
            :placeholder="t('order.transfer_payment_info')"
            @change="handleChangeTransferPaymentInfo"
          >
            <el-option
              v-for="item in transferPaymentInfoList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="state.transfer_payment_info_detail.detail.label"
          v-if="form.transfer_payment_info"
        >
          <el-input
            v-model="state.transfer_payment_info_detail.detail.value"
            type="textarea"
            disabled
            :rows="6"
          />
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="state.transfer_payment_info_detail.profile.label"
          v-if="form.transfer_payment_info"
        >
          <el-input
            v-model="state.transfer_payment_info_detail.profile.value"
            type="textarea"
            disabled
            :rows="3"
          />
        </el-form-item>

        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('order.owner')"
          required
        >
          <el-input v-model="state.inputDisplayText.owner" clearable disabled placeholder="">
            <template #append>
              <el-button size="small" text type="success" @click="handleOpenOwner">{{
                t('dealerAssetManagement.select')
              }}</el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('order.single_order_method')"
          required
        >
          <el-select
            v-model="form.single_order_method"
            :placeholder="t('order.single_order_method')"
          >
            <el-option
              v-for="item in singleOrderMethodList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item :class="isMobile ? 'mobile-item' : 'w-60%'" :label="t('order.partner')">
          <el-input v-model="state.inputDisplayText.partner" clearable disabled placeholder="">
            <template #append>
              <el-button size="small" text type="success" @click="handleOpenPartner">{{
                t('dealerAssetManagement.select')
              }}</el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('order.id_number')"
          prop="id_number"
          :required="form.contract_type == 1 ? true : false"
        >
          <el-input v-model="form.id_number" clearable :placeholder="t('order.id_number')" />
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('order.currency')"
          required
        >
          <el-select
            v-model="form.currency"
            :placeholder="t('order.currency')"
            @change="handleChangeCurrency"
          >
            <el-option
              v-for="item in currencyList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          class="mobile-item"
          :label="t('inventory.source_table')"
          required
          :class="isMobile ? 'mobile-item' : 'w-60%'"
        >
          <el-select v-model="form.source" :placeholder="t('inventory.source_table')" filterable>
            <el-option
              v-for="item in sourceTableList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </div>

      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] my-10px"></div>

      <!--      商品-->
      <div :class="isMobile ? 'form-section' : ''">
        <el-form-item class="m-t-20px" :label="t('dealerAssetManagement.commodity')">
          <el-button class="m-l-20px" type="primary" size="small" @click="handleOpenShop"
            >{{ t('dealerAssetManagement.select') }}
          </el-button>
        </el-form-item>

        <!-- 移动端商品卡片视图 -->
        <div v-if="isMobile && form.tableList.length" class="mobile-card">
          <el-card v-for="(item, index) in form.tableList" :key="item.unique" class="product-card">
            <template #header>
              <div class="card-header">
                <span class="product-name">{{ item.product_name }}</span>
                <el-button type="danger" @click="handleDelete(index)" size="small">
                  {{ t('wholesalOrder.delete') }}
                </el-button>
              </div>
            </template>

            <div class="card-content">
              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.warehouse') }}:</span>
                <span class="value">{{ useEnumeratePicker(warehouseList, item.wid) }}</span>
              </div>

              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.type') }}:</span>
                <span class="value">{{
                  useEnumeratePicker(warehouseTypeList, item.is_futures)
                }}</span>
              </div>

              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.sellableInventory') }}:</span>
                <span class="value">{{ item.quantity }}</span>
              </div>

              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.quantityPurchased') }}:</span>
                <div class="value">
                  <el-input-number
                    v-if="currentRow.pay_status == 3 || currentRow.pay_status == 4"
                    v-model="item!.pay_quantity"
                    :min="item.allow_zero_stock_sale == 1 ? 0 : 1"
                    :max="100000"
                    @change="handleCalcSinglePrice(item, index)"
                  />
                  <el-input-number
                    v-else
                    v-model="item!.pay_quantity"
                    :min="item.allow_zero_stock_sale == 1 ? 0 : 1"
                    :max="
                      item.allow_zero_stock_sale == 1
                        ? 100000
                        : item!.quantity
                          ? parseInt(item!.quantity as string)
                          : 100000
                    "
                    @change="handleCalcSinglePrice(item, index)"
                  />
                </div>
              </div>

              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.cost') }}:</span>
                <span class="value"
                  >{{ item.original_price }}({{ item.actual_quoted_currency_name }})</span
                >
              </div>

              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.discountedPrice') }}:</span>
                <span class="value"
                  >{{ item.original_actual_price }}({{ item.actual_quoted_currency_name }})</span
                >
              </div>

              <div class="info-row">
                <span class="label"
                  >{{
                    t('order.actual_selling_price') +
                    '[' +
                    useEnumeratePicker(currencyList, form.currency) +
                    ']'
                  }}:</span
                >
                <div class="value">
                  <el-input
                    v-model="item.actual_selling_price"
                    :clearable="false"
                    placeholder=" "
                  />
                </div>
              </div>
              <div class="info-row">
                <span class="label">{{ t('inventory.first_leg_logistics_fee') }}:</span>
                <span class="value">{{ item.first_leg_logistics_fee }}</span>
              </div>
              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.code') }}:</span>
                <span class="value">{{ item.product_code }}</span>
              </div>

              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.brand') }}:</span>
                <span class="value">{{ useEnumeratePicker(brandList, item.brand) }}</span>
              </div>

              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.computingPower') }}:</span>
                <span class="value">{{ item.hashrate }}</span>
              </div>

              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.warranty') }}:</span>
                <span class="value">{{ item.expiration_date }}</span>
              </div>

              <div class="info-row">
                <span class="label">{{ t('wholesalOrder.arrivalDate') }}:</span>
                <span class="value">{{ item.arrival_date }}</span>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 桌面端表格视图 -->
        <el-table
          v-if="!isMobile"
          :data="form.tableList"
          fit
          highlight-current-row
          stripe
          border
          show-summary
          :summary-method="getSummaries as any"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
        >
          <el-table-column
            :label="t('wholesalOrder.warehouse')"
            :width="calculateColumnWidth(form.tableList, 'warehouse', 2, 1)"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ useEnumeratePicker(warehouseList, row.wid) }}
            </template>
          </el-table-column>
          <el-table-column
            :label="t('wholesalOrder.name')"
            prop="product_name"
            :width="calculateColumnWidth(form.tableList, 'product_name')"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            :label="t('wholesalOrder.type')"
            :width="calculateColumnWidth(form.tableList, 'type')"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ useEnumeratePicker(warehouseTypeList, row.is_futures) }}
            </template>
          </el-table-column>
          <el-table-column
            :label="t('wholesalOrder.sellableInventory')"
            prop="quantity"
            :width="calculateColumnWidth(form.tableList, 'quantity', 1, 5)"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="t('wholesalOrder.quantityPurchased')"
            min-width="180"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row, $index }">
              <!-- 编辑时零库存不限制，否则最大值是可售库存和购买数量之和 -->
              <el-input-number
                v-model="row!.pay_quantity"
                :min="row.allow_zero_stock_sale == 1 ? 0 : 1"
                :max="row.allow_zero_stock_sale == 1 ? 100000 : countMax(row)"
                @change="handleCalcSinglePrice(row, $index)"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="t('wholesalOrder.cost')"
            prop="original_price"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ row.original_price }}({{ row.actual_quoted_currency_name }})
            </template>
          </el-table-column>
          <el-table-column
            :label="t('wholesalOrder.discountedPrice')"
            min-width="120"
            prop="original_actual_price"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ row.original_actual_price }}({{ row.actual_quoted_currency_name }})
            </template>
          </el-table-column>

          <el-table-column
            :label="
              t('order.actual_selling_price') +
              '[' +
              useEnumeratePicker(currencyList, form.currency) +
              ']'
            "
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              <el-input v-model="row.actual_selling_price" :clearable="false" placeholder=" " />
            </template>
          </el-table-column>
          <el-table-column
            :label="t('inventory.first_leg_logistics_fee')"
            prop="first_leg_logistics_fee"
            min-width="120"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="t('wholesalOrder.code')"
            prop="product_code"
            :width="calculateColumnWidth(form.tableList, 'code')"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="t('wholesalOrder.brand')"
            :width="calculateColumnWidth(form.tableList, 'brand')"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ useEnumeratePicker(brandList, row.brand) }}
            </template>
          </el-table-column>
          <el-table-column
            :label="t('wholesalOrder.computingPower')"
            prop="hashrate"
            :width="calculateColumnWidth(form.tableList, 'computingPower')"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="t('wholesalOrder.warranty')"
            prop="expiration_date"
            :width="calculateColumnWidth(form.tableList, 'warranty')"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="t('wholesalOrder.arrivalDate')"
            min-width="86px"
            prop="arrival_date"
            :width="calculateColumnWidth(form.tableList, 'arrival_date')"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            :label="t('order.realArrivalDate')"
            prop="real_arrival_date"
            min-width="86px"
            :show-overflow-tooltip="true"
          />

          <el-table-column fixed="right" :label="t('order.action')" width="100">
            <template #default="{ $index }">
              <el-button type="danger" @click="handleDelete($index)" size="small">
                {{ t('wholesalOrder.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-t-40px m-b-20px"></div>

      <!--      收货方式-->
      <div :class="isMobile ? 'form-section' : ''">
        <el-form-item
          :label="t('order.payment_deadline')"
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          prop="payment_deadline"
          required
        >
          <el-date-picker
            v-model="form.payment_deadline"
            type="date"
            :placeholder="t('order.payment_deadline')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          :label="t('order.shipping_start_date')"
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          prop="shipping_start_date"
          required
        >
          <el-date-picker
            v-model="form.shipping_start_date"
            type="date"
            :placeholder="t('order.shipping_start_date')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          :label="t('order.shipping_end_date')"
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          prop="shipping_end_date"
        >
          <el-date-picker
            v-model="form.shipping_end_date"
            type="date"
            :placeholder="t('order.shipping_end_date')"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 账单地址 -->
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('order.billing_address')"
        >
          <el-input v-model="form.billingAddress.address" disabled placeholder=" ">
            <template #append>
              <el-button size="small" text type="success" @click="handleSelectBillingAddress">
                {{ t('dealerAssetManagement.select') }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item :label="t('dealerAssetManagement.receiptMethod')">
          <el-radio-group
            :class="isMobile ? 'mobile-radio-group' : 'm-l-20px'"
            v-model="form.receiptMethod"
            @change="handleReceiptMethodChange"
          >
            <el-radio v-for="item in receiptMethodList" :key="item.value" :label="item.value"
              >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('dealerAssetManagement.deliveryAddress')"
          v-if="form.receiptMethod === 1"
        >
          <el-input v-model="form.deliveryAddress.address" disabled placeholder=" ">
            <template #append>
              <el-button size="small" text type="success" @click="handleSelectAddress">{{
                t('dealerAssetManagement.select')
              }}</el-button>
            </template>
          </el-input>
        </el-form-item>
      </div>

      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-b-20px" v-if="form.receiptMethod === 0"></div>
      <!--      自提地址-->
      <div v-if="form.receiptMethod === 0" :class="isMobile ? 'form-section' : ''">
        <el-form-item
          :label="t('dealerAssetManagement.pickUpAddress')"
          :class="isMobile ? '' : 'w-60%'"
        >
          <el-input
            :class="isMobile ? '' : ''"
            v-model="form.selfPickupInfo.pickUpAddress"
            disabled
            placeholder=" "
          />
        </el-form-item>
        <el-form-item
          :label="t('dealerAssetManagement.selfPickupInformation')"
          prop="selfPickupInfo.name"
          :class="isMobile ? '' : 'w-60%'"
        >
          <el-input
            :class="isMobile ? '' : ''"
            v-model="form.selfPickupInfo.name"
            :placeholder="t('dealerAssetManagement.nameMsg')"
          />
        </el-form-item>
        <el-form-item label=" " prop="selfPickupInfo.phone" :class="isMobile ? '' : 'w-60%'">
          <el-input
            v-model="form.selfPickupInfo.phone"
            :placeholder="t('dealerAssetManagement.phoneMsg')"
          />
        </el-form-item>
        <el-form-item label=" " prop="selfPickupInfo.passport" :class="isMobile ? '' : 'w-60%'">
          <el-input v-model="form.selfPickupInfo.passport" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label=" " :class="isMobile ? '' : 'w-60%'">
          <el-input
            v-model="form.selfPickupInfo.vehicleInfo"
            :placeholder="t('dealerAssetManagement.vehicleInfoMsg')"
          />
        </el-form-item>
      </div>

      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-b-20px" v-if="form.receiptMethod === 2"></div>
      <!--      自提地址-->

      <div v-if="form.receiptMethod === 2" :class="isMobile ? 'form-section' : ''">
        <el-form-item
          :label="t('dealerAssetManagement.information')"
          prop="selfPickupInfo.name"
          :class="isMobile ? '' : 'w-60%'"
        >
          <el-input
            :class="isMobile ? '' : ''"
            v-model="form.selfPickupInfo.name"
            :placeholder="t('dealerAssetManagement.nameMsg')"
          />
        </el-form-item>
        <el-form-item label=" " prop="selfPickupInfo.phone" :class="isMobile ? '' : 'w-60%'">
          <el-input
            v-model="form.selfPickupInfo.phone"
            :placeholder="t('dealerAssetManagement.phoneMsg')"
          />
        </el-form-item>
        <el-form-item label=" " prop="selfPickupInfo.passport" :class="isMobile ? '' : 'w-60%'">
          <el-input
            v-model="form.selfPickupInfo.passport"
            :placeholder="t('dealerAssetManagement.passportMsg')"
          />
        </el-form-item>
        <el-form-item label=" " :class="isMobile ? '' : 'w-60%'">
          <el-input
            v-model="form.selfPickupInfo.warehouseCode"
            :placeholder="t('dealerAssetManagement.warehouseCodeMsg')"
          />
        </el-form-item>
      </div>

      <div class="" v-if="form.receiptMethod === 0 || form.receiptMethod === 2">
        <el-form-item :label="t('payment.attachment')" :class="isMobile ? '' : 'w-60%'">
          <UploadFilesBase
            ref="uploadRef"
            class="w-full"
            :directory="19"
            :limit="9"
            :fileListMap="form.selfPickupInfo.annex_list"
            @upload-success-res="handleUploadCallback"
          /> </el-form-item
        >`
      </div>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-b-20px" v-if="form.receiptMethod === 1"></div>
      <!--        收货地址-->

      <div
        class="flex flex-col"
        v-if="form.receiptMethod === 1"
        :class="isMobile ? 'form-section' : ''"
      >
        <el-form-item :label="t('dealerAssetManagement.aging')">
          <el-radio-group
            :class="isMobile ? 'mobile-radio-group' : 'm-l-20px'"
            v-model="form.aging"
            @change="handleChangeAging"
          >
            <el-radio v-for="item in agingList" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="t('dealerAssetManagement.howToFileYourTaxes')">
          <el-radio-group
            :class="isMobile ? 'mobile-radio-group' : 'm-l-20px'"
            v-model="form.howToFileYourTaxes"
            @change="handleChangeTax"
          >
            <el-radio v-for="item in howToFileYourTaxesList" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <el-form-item
        :class="isMobile ? 'mobile-item' : 'w-60%'"
        :label="t('order.freight')"
        v-if="form.receiptMethod === 1"
        prop="deliveryAddress.freight"
      >
        <el-input
          v-model="form.deliveryAddress.freight"
          placeholder=" "
          @input="
            (e: string) =>
              (form.deliveryAddress.freight = e
                .replace(/[^\d.]/g, '')
                .replace(/\.{2,}/g, '.')
                .replace('.', '$#$')
                .replace(/\./g, '')
                .replace('$#$', '.')
                .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
                .replace(/^\./g, ''))
          "
        />
      </el-form-item>

      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-b-20px"></div>
      <div :class="isMobile ? 'form-section' : ''">
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('order.pay_terms')"
          required
        >
          <el-select v-model="form.pay_terms" :placeholder="t('order.pay_terms')">
            <el-option
              v-for="item in payTermsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('wholesalOrder.advance_amount')"
          v-if="form.pay_terms === 1"
        >
          <el-input-number
            class="!w-full"
            v-model="form.advance_amount"
            :min="0"
            :max="form.total_amount ? Number(form.total_amount) : 0"
            required
          />
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('inventory.first_leg_logistics_fee')"
        >
          <el-input v-model="firstLogisticsFeeTotal" placeholder="" disabled />
        </el-form-item>
        <el-form-item
          :class="isMobile ? 'mobile-item' : 'w-60%'"
          :label="t('wholesalOrder.total_amount')"
        >
          <el-input v-model="form.total_amount" placeholder="" disabled />
        </el-form-item>
        <el-form-item :class="isMobile ? 'mobile-item' : 'w-60%'" :label="t('order.is_sop')">
          <el-checkbox v-model="isSopChecked" @change="handleIsSopChange" />
        </el-form-item>
        <!--      备注-->
        <el-form-item :label="t('order.order_remark')">
          <el-input
            :class="isMobile ? '' : 'm-l-20px'"
            v-model="form.order_remark"
            type="textarea"
            :style="isMobile ? 'width: 100%' : 'width: 350px'"
            :autosize="{ minRows: 5, maxRows: 10 }"
            maxlength="600"
            :placeholder="t('order.order_remark')"
          />
        </el-form-item>
        <el-form-item :label="t('order.notes')">
          <el-input
            :class="isMobile ? '' : 'm-l-20px'"
            v-model="form.notes"
            type="textarea"
            :style="isMobile ? 'width: 100%' : 'width: 350px'"
            :autosize="{ minRows: 5, maxRows: 10 }"
            maxlength="600"
            :placeholder="t('order.notes')"
          />
        </el-form-item>
      </div>
    </el-form>
  </ContentDetailWrap>
  <!--  选择客户弹框-->
  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="getExposeCustomerData"
  />
  <!--  选择签订人弹框-->
  <DialogOperatorChecked
    ref="DialogOperatorCheckedRef"
    @expose-multiple-data="getExposeOperatorData"
  />

  <!--  选择负责人弹框-->
  <DialogOperatorChecked ref="DialogOwnerCheckedRef" @expose-multiple-data="getExposeOwnerData" />

  <!--  选择合伙人弹框-->
  <DialogOperatorChecked
    ref="DialogPartnerCheckedRef"
    :multiple="true"
    @expose-multiple-data="getExposePartnerData"
  />

  <!--  选择商品弹框-->
  <DialogShopChecked ref="DialogShopCheckedRef" @expose-multiple-data="getExposeMultipleData" />
  <!--  选择地址弹框-->
  <DialogSelectAddress
    ref="DialogSelectAddressRef"
    @expose-multiple-data="getExposeAddressData"
    :multiple="false"
  />
  <!--  选择账单地址弹框-->
  <DialogSelectBillingAddress
    ref="DialogSelectBillingAddressRef"
    @expose-multiple-data="getExposeBillingAddressData"
    :multiple="false"
  />
</template>
<script setup lang="ts">
import Decimal from 'decimal.js'
import DialogCustomerChecked from '../../Customer/Customer/components/DialogChecked/index.vue'
import DialogOperatorChecked from '../../Authorization/Operator/components/DialogChecked/index.vue'
import DialogShopChecked from './components/DialogShopChecked/index.vue'
import DialogSelectAddress from './components/DialogSelectAddress/index.vue'
import DialogSelectBillingAddress from './components/DialogSelectBillingAddress/index.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useEnumeratePicker, areIdsEqual } from '@/utils'
import { ElMessage, ElMessageBox, type FormRules, type FormInstance, ElLoading } from 'element-plus'
import {
  editDataApi,
  getDetailApi,
  getOrderEnumApi,
  getFreightApi,
  getPickUpAddressApi,
  hasPowerlineApi
} from '@/api/order'
import { getInventoryEnumApi } from '@/api/wholesalOrder'
import { getSelectApi as getCurrencySelectApi } from '@/api/transactionCurrency'
import { useDebounceFn } from '@vueuse/core'
import { getCurrentDate, formatToDate } from '@/utils/dateUtil'
import { useLocale } from '@/hooks/web/useLocale'
import { useLocaleStore } from '@/store/modules/locale'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
import { useAppStore } from '@/store/modules/app'
import { calculateColumnWidth } from '@/utils'

const localeStore = useLocaleStore()
const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const { t } = useI18n()
const { push, go } = useRouter()
const { query } = useRoute()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const isSopChecked = ref<boolean>(false)
const state = reactive({
  inputDisplayText: {
    signatory: '',
    owner: '',
    partner: ''
  },
  transfer_payment_info_detail: {
    // 付款信息显示数据
    list: [],
    detail: {
      label: '',
      value: ''
    },
    profile: {
      label: '',
      value: ''
    }
  }
})

const form = ref<Record<string, any>>({
  contract_type: 1, //'签署合同类型'
  source: 0, //来源 默认erp
  is_sop: 0, // 是否拼单采购 默认否
  signatory: '',
  order_no: '',
  signing_date: getCurrentDate(),
  single_order_method: 1,
  id_number: '', //统一社会信用代码/身份证号
  payment_deadline: '', //收款截止日期
  shipping_start_date: '', //发货起始日期
  shipping_end_date: '', //发货截止时间
  transfer_payment_info: '', //付款信息
  contract_signing_status: '', //合同签署状态
  // advance_pay_time: '', // 预付款时间
  currency: 214, // 客户付款币种
  owner: 0,
  partner: '',
  customer: {
    user_id: '',
    username: '',
    email: '',
    role: ''
  },
  tableList: [],
  receiptMethod: 1,
  selfPickupInfo: {
    pickUpAddress: '',
    name: '',
    phone: '',
    passport: '',
    warehouseCode: '',
    vehicleInfo: '',
    annex: '',
    annex_list: []
  },
  deliveryAddress: {
    id: '',
    address: '',
    freight: ''
  },
  aging: 1,
  howToFileYourTaxes: 1,
  order_remark: '',
  notes: '',
  billingAddress: {
    id: '',
    address: ''
  }
})
// 新增：订单编号编辑状态控制
const isOrderNoEditable = ref(false)
const toggleOrderNoEdit = () => {
  isOrderNoEditable.value = !isOrderNoEditable.value
}
const addressRow = ref<Record<string, any>>({})

const rules = ref<FormRules>({
  signatory: [
    {
      required: true,
      message: t('common.selectText') + t('order.signatory'),
      trigger: 'blur'
    }
  ],
  payment_deadline: [
    {
      required: true,
      message: t('common.selectText') + t('order.payment_deadline'),
      trigger: 'blur'
    }
  ],
  shipping_start_date: [
    {
      required: true,
      message: t('common.selectText') + t('order.shipping_start_date'),
      trigger: 'blur'
    }
  ],
  signing_date: [
    {
      required: true,
      message: t('common.selectText') + t('order.signing_date'),
      trigger: 'blur'
    }
  ],
  id_number: [
    {
      required: true,
      message: t('common.inputText') + t('order.id_number'),
      trigger: 'blur'
    }
  ],
  source: [
    {
      required: true,
      message: t('common.selectText') + t('inventory.source_table'),
      trigger: 'blur'
    }
  ],
  'selfPickupInfo.name': [
    {
      required: true,
      message: t('dealerAssetManagement.nameMsg'),
      trigger: 'blur'
    }
  ],
  'selfPickupInfo.phone': [
    {
      required: true,
      message: t('dealerAssetManagement.phoneMsg'),
      trigger: 'blur'
    }
  ],
  'selfPickupInfo.passport': [
    {
      required: true,
      message: t('dealerAssetManagement.passportMsg'),
      trigger: 'blur',
      // 仅当收货方式不为0时校验
      validator: (_rule: any, value: any, callback: any) => {
        if (form.value.receiptMethod === 0) {
          callback()
        } else if (!value) {
          callback(new Error(t('dealerAssetManagement.passportMsg')))
        } else {
          callback()
        }
      }
    }
  ],
  'deliveryAddress.freight': [
    {
      required: true,
      message: t('common.inputText') + t('order.freight'),
      trigger: 'blur'
    }
  ]
})

const DialogCustomerCheckedRef = ref<InstanceType<typeof DialogCustomerChecked>>()
const DialogOperatorCheckedRef = ref<InstanceType<typeof DialogOperatorChecked>>()
const DialogOwnerCheckedRef = ref<InstanceType<typeof DialogOperatorChecked>>() // 负责人
const DialogPartnerCheckedRef = ref<InstanceType<typeof DialogOperatorChecked>>() // 合伙人
const DialogShopCheckedRef = ref<InstanceType<typeof DialogShopChecked>>()
const DialogSelectAddressRef = ref<InstanceType<typeof DialogSelectAddress>>()
const DialogSelectBillingAddressRef = ref<InstanceType<typeof DialogSelectBillingAddress>>()

const brandList = ref<Array<Record<string, any>>>([])
const payTermsList = ref<Array<Record<string, any>>>([])
const sourceTableList = ref<Array<Record<string, any>>>([])
const warehouseList = ref<Array<Record<string, any>>>([])
const warehouseTypeList = ref<any[]>([])
const receiptMethodList = ref<Array<Record<string, any>>>([])
const agingList = ref<Array<Record<string, any>>>([])
const howToFileYourTaxesList = ref<Array<Record<string, any>>>([])
const contractTypeList = ref<Array<Record<string, any>>>([]) // 签署合同类型下拉数组
const singleOrderMethodList = ref<Array<Record<string, any>>>([]) //成单方式下拉数组
const currencyList = ref<Array<Record<string, any>>>([]) // 客户付款币种下拉数组
const transferPaymentInfoList = ref<Array<Record<string, any>>>([]) // 付款信息下拉数组
const operatorList = ref<Array<Record<string, any>>>([]) // 操作员列表

const countMax = (row: any) => {
  if (row.allow_zero_stock_sale == 1) {
    return 100000
  }
  const pay_quantity =
    currentRow.value.edit_list.find(
      (item: any) => item.product_id == row.product_id && item.wid == row.wid
    )?.pay_quantity || 0
  return currentRow.value.pay_status == '3' || currentRow.value.pay_status == '4'
    ? Number(row.quantity) + Number(pay_quantity)
    : Number(row.quantity)
}

// 切换合同类型
const handleChangeContractType = (value: any) => {
  if (1 == value) {
    form.value.transfer_payment_info = ''
  }
  console.log(form.value.transfer_payment_info)
}
// 切换付款信息
const handleChangeTransferPaymentInfo = (value: any) => {
  state.transfer_payment_info_detail.list.map((item: any) => {
    if (item.value == value) {
      state.transfer_payment_info_detail.detail.label = item.label.detail_label
      state.transfer_payment_info_detail.detail.value = item.label.detail_value
      state.transfer_payment_info_detail.profile.label = item.label.profile_label
      state.transfer_payment_info_detail.profile.value = item.label.profile_value
    }
  })
}

// 切换客户付款币种
const handleChangeCurrency = (value: any) => {
  form.value.tableList = []
}

// 处理是否拼单采购复选框变化
const handleIsSopChange = (checked: boolean) => {
  form.value.is_sop = checked ? 1 : 0
}

//打开选择客户弹框
const handleOpenCustomer = () => {
  nextTick(() => {
    DialogCustomerCheckedRef!.value!.dialogVisible = true
    DialogCustomerCheckedRef!.value!.initialize(
      form.value.customer.user_id
        ? [
            {
              ...form.value.customer,
              id: form.value.customer.user_id
            }
          ]
        : []
    )
  })
}

//打开选择签订人弹框
const handleOpenSignatory = () => {
  nextTick(() => {
    DialogOperatorCheckedRef.value!.dialogVisible = true
    DialogOperatorCheckedRef.value!.initialize(
      form.value.signatory ? [{ id: form.value.signatory }] : []
    )
  })
}

//打开选择负责人弹框
const handleOpenOwner = () => {
  nextTick(() => {
    DialogOwnerCheckedRef.value!.dialogVisible = true
    DialogOwnerCheckedRef.value!.initialize(form.value.owner ? [{ id: form.value.owner }] : [])
  })
}

//打开选择合伙人弹框
const handleOpenPartner = () => {
  nextTick(() => {
    DialogPartnerCheckedRef.value!.dialogVisible = true
    DialogPartnerCheckedRef.value!.initialize(
      form.value.partner
        ? form.value.partner.split(',').map((item) => ({ id: Number(item.trim()) }))
        : []
    )
  })
}

//打开选择商品弹框
const handleOpenShop = () => {
  if (!form.value.customer.user_id) return ElMessage.warning('请先选择客户')
  nextTick(() => {
    DialogShopCheckedRef!.value!.dialogVisible = true
    DialogShopCheckedRef!.value!.initialize(form.value.tableList, form.value.currency)
  })
}

//打开选择地址弹框
const handleSelectAddress = () => {
  if (!form.value.customer.user_id) return ElMessage.warning('请先选择客户')
  if (!form.value.tableList.length) return ElMessage.warning('请先选择商品')
  nextTick(() => {
    DialogSelectAddressRef!.value!.dialogVisible = true
    DialogSelectAddressRef!.value!.initialize(
      form.value.customer.user_id,
      form.value.deliveryAddress.id
        ? [
            {
              id: form.value.deliveryAddress.id
            }
          ]
        : []
    )
  })
}

//切换时效
const handleChangeAging = () => {
  if (!form.value.customer.user_id) {
    form.value.aging = form.value.aging === 1 ? 2 : 1
    return ElMessage.warning('请选择客户')
  }
  if (!form.value.tableList.length) {
    form.value.aging = form.value.aging === 1 ? 2 : 1
    return ElMessage.warning('请选择商品')
  }
  if (!form.value.deliveryAddress.id) {
    form.value.aging = form.value.aging === 1 ? 2 : 1
    return ElMessage.warning('请选择收货地址')
  }
  getShippingRates()
}

//切换报税方式
const handleChangeTax = () => {
  if (!form.value.customer.user_id) {
    form.value.howToFileYourTaxes = form.value.howToFileYourTaxes === 1 ? 2 : 1
    return ElMessage.warning('请选择客户')
  }
  if (!form.value.tableList.length) {
    form.value.howToFileYourTaxes = form.value.howToFileYourTaxes === 1 ? 2 : 1
    return ElMessage.warning('请选择商品')
  }
  if (!form.value.deliveryAddress.id) {
    form.value.howToFileYourTaxes = form.value.howToFileYourTaxes === 1 ? 2 : 1
    return ElMessage.warning('请选择收货地址')
  }
  getShippingRates()
}

//切换收货方式
const handleReceiptMethodChange = async (e: number) => {
  if (e != 0) {
    form.value.selfPickupInfo.vehicleInfo = ''
  }
  if (e != 2) {
    form.value.selfPickupInfo.warehouseCode = ''
  }
  if (e === 0) {
    if (!form.value.tableList.length) {
      ElMessage.warning('请先选择商品')
      form.value.receiptMethod = 1
      return
    }
    const resp = await getPickUpAddressApi(form.value.tableList[0].wid)
    form.value.selfPickupInfo.pickUpAddress = resp.data.address
  }
}

//获取运费
const getShippingRates = async () => {
  let loadingInstance = {} as Record<string, any>
  try {
    loading.value = true

    const params = {
      currency: form.value.currency,
      terms: form.value.howToFileYourTaxes,
      to_nation: addressRow.value.to_nation,
      prescription: form.value.aging,
      product_list: form.value.tableList.flatMap((item: any) => [
        {
          id: item.product_id,
          wid: item.wid,
          num: item.pay_quantity,
          billing_weight: item.billing_weight,
          free_shipping: !!item.free_shipping,
          apply_rules: !!item.apply_rules
        }
      ])
    }
    loadingInstance = ElLoading.service({
      text: '正在查询运费，请稍候',
      background: 'rgba(0, 0, 0, 0.7)',
      fullscreen: true,
      lock: true
    })
    const freightResp = await getFreightApi(params)
    form.value.deliveryAddress.freight = freightResp.data.logistics_fee
    await nextTick(() => {
      formRef.value!.clearValidate(['deliveryAddress.freight'])
      loadingInstance.close()
    })
  } catch (e) {
    await nextTick(() => {
      loadingInstance.close()
    })
  } finally {
    loading.value = false
  }
}

//计算折扣价格
const handleCalcSinglePrice = useDebounceFn((row: Record<string, any>, index: number) => {
  console.log(row, index)
  if (row.discount_price && row.discount_price.length) {
    const min = Math.min(...row.discount_price.map((item: any) => item.num))
    const isCurrent = row.discount_price.find((item: any) => item.num === row.pay_quantity)
    const minus = row.discount_price.filter((item: any) => item.num < row.pay_quantity).pop()
    console.log(form.value.customer.role)
    if (form.value.customer.role === 'distributor') {
      const levelMin = row.discount_price.reduce((min: any, current: any) => {
        return min === undefined || current.level < min.level ? current : min
      }, undefined)
      if (isCurrent) {
        console.log('isCurrent', isCurrent)
        form.value.tableList[index].original_actual_price = isCurrent.price
        form.value.tableList[index].actual_selling_price = isCurrent.discount_actual_selling_price
        if (Object.keys(addressRow.value).length) getShippingRates()
        return
      }
      if (minus) {
        console.log('minus', minus)
        form.value.tableList[index].original_actual_price = minus.price
        form.value.tableList[index].actual_selling_price = minus.discount_actual_selling_price
        if (Object.keys(addressRow.value).length) getShippingRates()
        return
      }
      if (row.pay_quantity < min) {
        console.log('minus', levelMin)
        form.value.tableList[index].original_actual_price = levelMin.price
        if (levelMin.discount_actual_selling_price) {
          form.value.tableList[index].actual_selling_price = levelMin.discount_actual_selling_price
        }
        if (Object.keys(addressRow.value).length) getShippingRates()
        return
      }
    } else {
      if (isCurrent) {
        console.log(111, isCurrent)
        form.value.tableList[index].original_actual_price = isCurrent.price
        form.value.tableList[index].actual_selling_price = isCurrent.discount_actual_selling_price
        if (Object.keys(addressRow.value).length) getShippingRates()
        return
      }
      if (minus) {
        console.log(222, minus)
        form.value.tableList[index].original_actual_price = minus.price
        form.value.tableList[index].actual_selling_price = minus.discount_actual_selling_price
        if (Object.keys(addressRow.value).length) getShippingRates()
        return
      }
      if (row.pay_quantity < min) {
        console.log(333, row)
        form.value.tableList[index].original_actual_price = row.original_price
        form.value.tableList[index].actual_selling_price = row.original_actual_selling_price
        if (Object.keys(addressRow.value).length) getShippingRates()
        return
      }
    }
  } else {
    if (Object.keys(addressRow.value).length) getShippingRates()
  }
}, 500)

const uploadRef = ref<any>(null)
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      if (!form.value.customer.user_id) return ElMessage.warning('请选择客户')
      if (!form.value.owner) return ElMessage.warning('请选择负责人')
      if (2 == form.value.contract_type && !form.value.transfer_payment_info) {
        return ElMessage.warning('请选择付款信息')
      }
      if (!form.value.tableList.length) return ElMessage.warning('请选择商品')
      if (
        !form.value.tableList.every((item: Record<string, any>) => !!item.original_actual_price)
      ) {
        return ElMessage.warning('折扣价格不能为空')
      }
      if (
        form.value.shipping_start_date &&
        form.value.shipping_end_date &&
        form.value.shipping_start_date >= form.value.shipping_end_date
      ) {
        return ElMessage.warning(t('order.shipping_end_date') + '无效')
      }
      if (form.value.receiptMethod === 1 && !form.value.deliveryAddress.id) {
        return ElMessage.warning('请选择收货地址')
      }
      let result = await uploadRef.value?.uploadImg()
      console.log('result', result)
      if (result) {
        ElMessage.warning('上传中,请稍等')
        return
      }
      let anexStr = ''
      if (form.value.receiptMethod === 0 || form.value.receiptMethod === 2) {
        anexStr = form.value.selfPickupInfo.annex_list?.map((item: any) => item.id).join(',')
      }
      console.log(anexStr, 'anexStr')
      const params = {
        contract_type: form.value.contract_type,
        signatory: form.value.signatory,
        order_no: form.value.order_no,
        signing_date: formatToDate(form.value.signing_date) ?? '',
        owner: form.value.owner,
        partner: form.value.partner,
        single_order_method: form.value.single_order_method,
        id_number: form.value.id_number,
        payment_deadline: formatToDate(form.value.payment_deadline) ?? '',
        shipping_start_date: formatToDate(form.value.shipping_start_date) ?? '',
        shipping_end_date: formatToDate(form.value.shipping_end_date) ?? '',
        transfer_payment_info: form.value.transfer_payment_info,
        contract_signing_status: form.value.contract_signing_status,
        currency: form.value.currency,

        wid: form.value.tableList[0].wid || '',
        user_id: form.value.customer.user_id,
        list: form.value.tableList,
        delivery_method: form.value.receiptMethod,
        order_remark: form.value.order_remark,
        notes: form.value.notes,
        pay_terms: form.value.pay_terms,
        advance_amount: form.value.pay_terms == 1 ? form.value.advance_amount : 0,
        first_leg_logistics_fee: firstLogisticsFeeTotal.value,
        annex: anexStr,
        source: form.value.source,
        // 自提
        ...(form.value.receiptMethod === 0 && { name: form.value.selfPickupInfo.name }),
        ...(form.value.receiptMethod === 0 && { phone: form.value.selfPickupInfo.phone }),
        ...(form.value.receiptMethod === 0 && { passport: form.value.selfPickupInfo.passport }),
        ...(form.value.receiptMethod === 0 && {
          vehicle: form.value.selfPickupInfo.vehicleInfo
        }),
        // 仓内过货
        ...(form.value.receiptMethod === 2 && { name: form.value.selfPickupInfo.name }),
        ...(form.value.receiptMethod === 2 && { phone: form.value.selfPickupInfo.phone }),
        ...(form.value.receiptMethod === 2 && { passport: form.value.selfPickupInfo.passport }),
        ...(form.value.receiptMethod === 2 && {
          warehouse_code: form.value.selfPickupInfo.warehouseCode
        }),
        //快递
        ...(form.value.receiptMethod === 1 && { address_id: form.value.deliveryAddress.id }),
        ...(form.value.receiptMethod === 1 && {
          logistics_fee: form.value.deliveryAddress.freight
        }),
        ...(form.value.receiptMethod === 1 && { prescription: form.value.aging }),
        ...(form.value.receiptMethod === 1 && {
          delivery_terms: form.value.howToFileYourTaxes
        }),
        billing_address_id: form.value.billingAddress.id,
        is_sop: form.value.is_sop ? 1 : 0
      } as unknown as Record<string, any>
      let res = await hasPowerlineApi({
        ids: form.value.tableList.map((item: any) => item.product_id).join(',')
      })
      if (res.code === 0) {
        if (res.data?.not_powerline?.length > 0 || res.data?.not_powersource?.length > 0) {
          let powerObj = res.data
          let messageHtml = '<div style="padding-bottom: 20px;">'
          if (powerObj?.not_powersource?.length) {
            messageHtml += '<p>以下商品无电源:</p>'
            messageHtml += '<ul style="margin: 10px 0; padding-left: 20px;">'
            // 假设params.list是一个包含商品信息的数组，每个商品有sku, cname等属性
            powerObj.not_powersource.forEach((product: any) => {
              // 检查商品是否有电源线或电源的信息，这里简化为检查是否存在特定属性
              messageHtml += `<li>${product.cname}</li>`
            })
            messageHtml += '</ul>'
          }
          if (powerObj?.not_powerline?.length) {
            messageHtml += '<p>以下商品无电源线:</p>'
            messageHtml += '<ul style="margin: 10px 0; padding-left: 20px;">'
            // 假设params.list是一个包含商品信息的数组，每个商品有sku, cname等属性
            powerObj.not_powerline.forEach((product: any) => {
              // 检查商品是否有电源线或电源的信息，这里简化为检查是否存在特定属性
              messageHtml += `<li>${product.cname}</li>`
            })
            messageHtml += '</ul>'
          }
          messageHtml += '</div>'
          console.log(messageHtml)
          ElMessageBox.confirm(messageHtml, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            customClass: 'msg-wrap'
          }).then(async () => {
            console.log('确定')
            const resp = await editDataApi(parseInt(query.id as string), params)
            if (resp.code === 0) {
              ElMessage.success(t('order.editSucMsg'))
              push('/order/order-management')
            }
          })
        } else {
          const resp = await editDataApi(parseInt(query.id as string), params)
          if (resp.code === 0) {
            ElMessage.success(t('order.editSucMsg'))
            push('/order/order-management')
          }
        }
      }
    }
  })
}

//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.customer.user_id && form.value.customer.user_id !== val[0].id) {
    form.value.tableList = []
    form.value.deliveryAddress = {
      id: '',
      address: '',
      freight: ''
    }
    addressRow.value = {}
  }
  form.value.customer.user_id = val[0].id
  form.value.customer.username = val[0].cusname
  form.value.customer.email = val[0].email
  form.value.customer.role = val[0].role
  form.value.owner = val[0].owner_id
  state.inputDisplayText.owner =
    operatorList.value.find((item: any) => item.value === val[0].owner_id)?.label || ''
  form.value.partner = val[0].partner.join(',')
  state.inputDisplayText.partner = val[0].partner
    .map(
      (partnerId: any) =>
        operatorList.value.find((item: any) => item.value === partnerId)?.label || ''
    )
    .filter((label: string) => label)
    .join(',')
}

//接收勾选中的签订人
const getExposeOperatorData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.signatory && form.value.signatory !== val[0].id) {
  }
  form.value.signatory = val[0].id
  state.inputDisplayText.signatory = val[0].cname
}

//接收勾选中的负责人
const getExposeOwnerData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.owner && form.value.owner !== val[0].id) {
  }
  form.value.owner = val[0].id
  state.inputDisplayText.owner = val[0].cname
}

//接收勾选中的合伙人
const getExposePartnerData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.partner && form.value.partner !== val[0].id) {
  }
  form.value.partner = val.map((item: any) => item.id).join(',')
  state.inputDisplayText.partner = val.map((item: any) => item.cname).join(',')
}

//接收勾选中的商品
const getExposeMultipleData = (val: any[]) => {
  if (!val || !val.length) return
  const copyData = JSON.parse(JSON.stringify(form.value.tableList))
  const mergeData = copyData.concat(val)

  const duplicates = form.value.tableList.map((item: Record<string, any>) => item.unique)
  form.value.tableList = val.flatMap((item: Record<string, any>) =>
    duplicates.includes(item.unique)
      ? [form.value.tableList.find((v: Record<string, any>) => item.unique === v.unique) || null]
      : [
          {
            ...item,
            pay_quantity: 1,
            original_actual_price: throughRolesDiscountedPrices(item),
            actual_selling_price: throughRolesActualSellingPrice(item)
          }
        ]
  )

  if (Object.keys(addressRow.value).length) {
    if (!copyData.length || !areIdsEqual(mergeData, 'wid')) getShippingRates()
  }
}

//通过角色返回折扣价格
const throughRolesDiscountedPrices = (item: Record<string, any>) => {
  let discountPrice: string | number = ''
  if (item.discount_price && item.discount_price.length) {
    if (form.value.customer.role === 'distributor') {
      discountPrice = item.discount_price.reduce((min: any, current: any) => {
        return min === undefined || current.level < min.level ? current : min
      }, undefined).price
    } else {
      discountPrice = item.original_price
    }
  }
  return discountPrice
}

//通过角色返回实际售卖价格
const throughRolesActualSellingPrice = (item: Record<string, any>) => {
  let actualSellingPrice: string | number = ''
  if (item.discount_price && item.discount_price.length) {
    console.log(form.value.customer.role)
    if (form.value.customer.role === 'distributor') {
      actualSellingPrice = item.discount_price.reduce((min: any, current: any) => {
        return min === undefined || current.level < min.level ? current : min
      }, undefined).discount_actual_selling_price
    } else {
      actualSellingPrice = item.original_actual_selling_price
    }
  }
  return actualSellingPrice
}

//接收勾选中的收货地址
const getExposeAddressData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.deliveryAddress.id = val[0].id
  form.value.deliveryAddress.address = val[0].address
  addressRow.value = val[0]
  getShippingRates()
}

const getExposeBillingAddressData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.billingAddress.id = val[0].id
  form.value.billingAddress.address = val[0].address
}
//删除某一行
const handleDelete = (index: number) => {
  ElMessageBox.confirm(t('purchase.logistics.confirmDeletion'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      form.value.tableList.splice(index, 1)
      if (!form.value.tableList.length) {
        form.value.receiptMethod = 1
        form.value.deliveryAddress.freight = ''
      }
    })
    .catch(() => {})
}

//列表合计
const firstLogisticsFeeTotal = ref(0)
const getSummaries = (param: Record<string, any>) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  const columnList: number[] = [1, 2, 3]
  columns.forEach((column: Record<string, any>, index: number) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'underline', textAlign: 'center' } }, [
        '合计'
      ])
      return
    }
    if (columnList.includes(index)) {
      sums[index] = h('div', { style: { textAlign: 'center' } }, [])
      return
    }
    if (index === 4) {
      const values = data.flatMap((item: Record<string, any>) => [item['pay_quantity']])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0).add(
            new Decimal(curr ? parseFloat(curr) : 0)
          )
        }, 0)}`
      ])
    }
    if (index === 5) {
      const values = data.flatMap((item: Record<string, any>) => [
        item['original_price'] * item['pay_quantity']
      ])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0)
            .add(new Decimal(curr ? parseFloat(curr) : 0))
            .toFixed(2)
        }, 0)}`
      ])
    }
    if (index === 6) {
      const values = data.flatMap((item: Record<string, any>) => [
        item['original_actual_price'] * item['pay_quantity']
      ])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0)
            .add(new Decimal(curr ? parseFloat(curr) : 0))
            .toFixed(2)
        }, 0)}`
      ])
    }
    if (index === 7) {
      const values = data.flatMap((item: Record<string, any>) => [
        item['actual_selling_price'] * item['pay_quantity']
      ])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0)
            .add(new Decimal(curr ? parseFloat(curr) : 0))
            .toFixed(2)
        }, 0)}`
      ])
    }
    if (index === 8) {
      const values = data.flatMap((item: Record<string, any>) => [
        item['first_leg_logistics_fee'] * item['pay_quantity']
      ])
      firstLogisticsFeeTotal.value = values
        .reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0).add(
            new Decimal(curr ? parseFloat(curr) : 0)
          )
        }, 0)
        .toFixed(2)
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${firstLogisticsFeeTotal.value}`
      ])
    }
  })
  return sums
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getOrderEnumApi({ field: 'all' })
  brandList.value = resp.data.brand
  payTermsList.value = resp.data.pay_terms
  receiptMethodList.value = resp.data.delivery_method
  agingList.value = resp.data.prescription
  howToFileYourTaxesList.value = resp.data.delivery_terms
  contractTypeList.value = resp.data.contract_type
  singleOrderMethodList.value = resp.data.single_order_method
  transferPaymentInfoList.value = resp.data.transfer_payment_info
  state.transfer_payment_info_detail.list = resp.data.transfer_payment_info_detail
  sourceTableList.value = resp.data.source
  const Currencyresp = await getCurrencySelectApi({})
  currencyList.value = Currencyresp.data.list
  const inventoryResp = await getInventoryEnumApi({ field: 'all' })
  warehouseList.value = inventoryResp.data.wid
  warehouseTypeList.value = inventoryResp.data.is_futures
  const operatorResp = await getOperatorSelectListApi({})
  operatorList.value = operatorResp.data.list
  await getEcho()
}

//回显
const currentRow = ref<any>({})
const getEcho = async () => {
  const resp = await getDetailApi(query.id as string)
  currentRow.value = JSON.parse(JSON.stringify(resp.data))

  form.value.shipping_end_date = resp.data.edit.shipping_end_date
  form.value.signatory = resp.data.edit.signatory
  form.value.order_no = resp.data.order_no
  state.inputDisplayText.signatory = resp.data.edit.signatory_value
  form.value.id_number = resp.data.edit.id_number
  form.value.payment_deadline = resp.data.edit.payment_deadline
  form.value.shipping_start_date = resp.data.edit.shipping_start_date
  form.value.contract_type = resp.data.edit.contract_type
  form.value.currency = resp.data.edit.currency

  if (resp.data.edit.transfer_payment_info) {
    form.value.transfer_payment_info = parseInt(resp.data.edit.transfer_payment_info)
    handleChangeTransferPaymentInfo(form.value.transfer_payment_info)
  }

  if (resp.data.edit.owner) {
    form.value.owner = resp.data.edit.owner
    state.inputDisplayText.owner = useEnumeratePicker(operatorList.value, form.value.owner)
  }

  if (resp.data.edit.partner) {
    form.value.partner = resp.data.edit.partner
    state.inputDisplayText.partner = resp.data.edit.partner.split(',').map((item) => {
      // 确保每个 item 传入 useEnumeratePicker 时是合法的
      return useEnumeratePicker(operatorList.value, Number(item))
    })
  }

  form.value.customer.user_id = resp.data.edit.user_id
  form.value.customer.role = resp.data.edit.role
  form.value.customer.username = resp.data.edit.user
  form.value.customer.email = resp.data.edit.email
  form.value.tableList = resp.data.edit_list
  form.value.receiptMethod = resp.data.edit.delivery_method
  form.value.order_remark = resp.data.order_remark
  form.value.notes = resp.data.notes
  form.value.pay_terms = resp.data.pay_terms
  form.value.advance_amount = resp.data.advance_amount ? Number(resp.data.advance_amount) : 0
  form.value.source = resp.data.source
  form.value.is_sop = resp.data.is_sop ? 1 : 0
  isSopChecked.value = form.value.is_sop === 1

  if (resp.data.edit.delivery_method === 0) {
    form.value.selfPickupInfo.name = resp.data.edit.name
    form.value.selfPickupInfo.phone = resp.data.edit.phone
    form.value.selfPickupInfo.passport = resp.data.edit.passport
    form.value.selfPickupInfo.vehicleInfo = resp.data.edit.vehicle
    form.value.selfPickupInfo.annex_list = resp.data.pickup[0]?.annex_list
    await handleReceiptMethodChange(resp.data.edit.delivery_method)
  } else if (resp.data.edit.delivery_method === 2) {
    form.value.selfPickupInfo.name = resp.data.edit.name
    form.value.selfPickupInfo.phone = resp.data.edit.phone
    form.value.selfPickupInfo.passport = resp.data.edit.passport
    form.value.selfPickupInfo.warehouseCode = resp.data.edit.warehouse_code
    form.value.selfPickupInfo.annex_list = resp.data.pickup[0]?.annex_list
    await handleReceiptMethodChange(resp.data.edit.delivery_method)
  } else {
    form.value.deliveryAddress.id = resp.data.address_id
    form.value.deliveryAddress.freight = resp.data.edit.logistics_fee
    form.value.deliveryAddress.address = resp.data.edit.address
    form.value.aging = resp.data.edit.prescription
    form.value.howToFileYourTaxes = resp.data.edit.delivery_terms
    if (resp.data.address_id && resp.data.country_id) {
      addressRow.value = {
        id: resp.data.address_id,
        country_id: resp.data.country_id,
        to_nation: resp.data.country_id
      }
    }
  }
  if (resp.data.edit.billing_address_id) {
    form.value.billingAddress.id = resp.data.edit.billing_address_id
    form.value.billingAddress.address = resp.data.edit.billing_address
  }
}

//打开选择账单地址弹框
const handleSelectBillingAddress = () => {
  if (!form.value.customer.user_id) return ElMessage.warning('请先选择客户')
  nextTick(() => {
    DialogSelectBillingAddressRef!.value!.dialogVisible = true
    DialogSelectBillingAddressRef!.value!.initialize(
      form.value.customer.user_id,
      form.value.billingAddress.id
        ? [
            {
              id: form.value.billingAddress.id
            }
          ]
        : []
    )
  })
}

onMounted(() => {
  getDropDownBoxInfo()
})
// const currentLang = ref('')
// watch(
//   () => form.value.contract_type,
//   (newVal) => {
//     if (!currentLang.value) {
//       currentLang.value = localeStore.getCurrentLocale.lang
//     }
//     const locale = newVal === 2 ? 'en' : 'zh-CN'
//     const { changeLocale } = useLocale()
//     changeLocale(locale)
//   },
//   {
//     immediate: true
//   }
// )
watchEffect(() => {
  let shopPrice = 0
  if (form.value.tableList && form.value.tableList.length) {
    const values = form.value.tableList.flatMap((item: Record<string, any>) => [
      Number(item['actual_selling_price']) * Number(item['pay_quantity'])
    ])
    shopPrice = values.reduce((acc, val) => acc + val, 0)
  }
  // 移动端的话计算下统计
  if (isMobile.value) {
    firstLogisticsFeeTotal.value = form.value.tableList.reduce(
      (acc, item) => acc + item.first_leg_logistics_fee * item.pay_quantity,
      0
    )
  }
  let freight = Number(form.value.deliveryAddress.freight) || 0
  form.value.total_amount = shopPrice * 1 + freight * 1 + firstLogisticsFeeTotal.value * 1
  if (form.value.total_amount < form.value.advance_amount) {
    form.value.advance_amount = form.value.total_amount
  }
})
//上传成功以后回调
const handleUploadCallback = (val: any) => {
  console.log('val3333344', val)
  form.value.selfPickupInfo.annex_list.push(...val)
  console.log('val33333', val, form.value.selfPickupInfo.annex_list)
}
// onUnmounted(() => {
//   // 组件销毁时恢复原来的语言设置
//   if (currentLang.value) {
//     const { changeLocale } = useLocale()
//     changeLocale(currentLang.value as LocaleType)
//     currentLang.value = ''
//   }
// })
// onBeforeRouteLeave(() => {
//   // 组件销毁时恢复原来的语言设置
//   if (currentLang.value) {
//     const { changeLocale } = useLocale()
//     changeLocale(currentLang.value as LocaleType)
//     currentLang.value = ''
//   }
// })
</script>

<style lang="less">
.msg-wrap {
  width: 600px;
  max-width: initial;
}
</style>
